﻿using System.Data;
using YNCNumberSys.db;
using YNCNumberSys.Entity;

namespace YNCNumberSys.DbDal
{
    public class CodeDal
    {
        private CommandManager commandManager = new CommandManager();
        private ConnectionManager connectionManager = new ConnectionManager();
        /// <summary>
        /// 获取位数和上限值。
        /// </summary>
        /// <returns></returns>
        public CodeEntity GetCodeEntity()
        {
            string sql = string.Format(@"SELECT [编码位数]
                                               ,[上限值]
                                          FROM[YNCNumberSys].[dbo].[编码位数]; ");
            DataTable dt = commandManager.ExecuteNonQuery(connectionManager.getConnection(), sql, "编码位数");
            CodeEntity codeentity = new CodeEntity();
            if(dt.Rows.Count>0)
            {
                codeentity.Digit = (int)dt.Rows[0]["编码位数"];
                codeentity.Limit = (int)dt.Rows[0]["上限值"];
                return codeentity;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 更新位数和上限值。
        /// </summary>
        /// <param name="ent"></param>
        /// <returns></returns>
        public bool UpdateCodeEntity(CodeEntity ent)
        {
            string insertSql = string.Format(
               @"INSERT INTO [YNCNumberSys].[dbo].[编码位数]
                           ([编码位数]
                           ,[上限值])
                     VALUES
                           ('{0}'
                           ,'{1}'); "
                           ,ent.Digit
                           ,ent.Limit);

            string updateSql = string.Format(
               @"UPDATE [YNCNumberSys].[dbo].[编码位数]
                       SET [编码位数] = {0}
                          ,[上限值] = {1} "
                           , ent.Digit
                           , ent.Limit);

            string selectSQL = string.Empty;
            selectSQL = string.Format(@"if NOT exists(SELECT Top 1 * FROM [YNCNumberSys].[dbo].[编码位数]) ");
            string strSql = selectSQL + " " + insertSql + "ELSE " + updateSql + ";";
            int row = commandManager.ExecuteScalar(connectionManager.getConnection(), strSql);
            return row == 1 ? true : false;
        }
    }
}
